﻿/// <reference path="datalayer.js" />
(function () {
    var soundTilesList = new WinJS.Binding.List([]);

    var loadSoundTiles = function () {
        var soundTiles = Data.getSoundTiles();

        var currentCount = soundTilesList.dataSource.list.length;
        soundTilesList.splice(0, currentCount);

        for (var i = 0; i < soundTiles.length; i++) {
            soundTilesList.push(WinJS.Binding.as(soundTiles[i]));
        }
    };

    var getInstanceByKeyBind = function (keyBind) {
        var elems = soundTilesList.dataSource.list;
        for (var i = 0; i < elems.length; i++) {
            if (elems.getAt(i).keyBind === keyBind) {
                return elems.getAt(i);
                break;
            }
        }
    }

    var addSoundTile = function (soundSource, keyBind, soundType, soundName) {
        Data.addSoundTile(new Models.SoundTileModel(soundSource, keyBind, soundType, soundName));
    };

    var searchQuery = WinJS.Binding.as({ queryText: "" });

    var filteredSoundTiles = soundTilesList.createFiltered(function (item) {
        var queryIndexInItemString = item.keyBind.toLowerCase().indexOf(searchQuery.queryText);

        var isSelected = queryIndexInItemString > -1;

        return isSelected;
    });

    var changeSearchQuery = function (text) {
        searchQuery.queryText = text.toLowerCase();
        soundTilesList.notifyReload();
    }

    var submitQuery = function (query) {
        searchQuery.queryText = query.queryText.toLowerCase();
        soundTilesList.notifyReload();
    }

    WinJS.Namespace.define("ViewModels", {
        loadSoundTiles: loadSoundTiles,
        soundTiles: soundTilesList,
        addSoundTile: addSoundTile,
        getInstanceByKeyBind: getInstanceByKeyBind,
        searchSoundTiles: filteredSoundTiles,
        submitSearchText: changeSearchQuery,
        submitSearchQuery: submitQuery,
        searchQuery: searchQuery
    });
})();